import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import * as CryptoJS from 'crypto-js';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {
    // 初始化添加默认用户
    this.initDefaultUser();
  }

  async findOne(username: string, password: string): Promise<User> {
    console.log('Finding user with:', { username, password });
    const query = { where: { username, password } };
    console.log('Query:', JSON.stringify(query));

    const user = await this.usersRepository.findOne(query);
    console.log('Found user from DB:', user);
    return user;
  }

  async findByUsername(username: string): Promise<User> {
    console.log('Finding user by username:', username);
    return this.usersRepository.findOne({ where: { username } });
  }

  async findById(id: number): Promise<User> {
    console.log('Finding user by id:', id);
    return this.usersRepository.findOne({ where: { id } });
  }

  async register(registerDto: any): Promise<User> {
    const { username, password, nickname } = registerDto;

    // 检查用户名是否已存在
    const existingUser = await this.findByUsername(username);
    if (existingUser) {
      throw new Error('用户名已存在');
    }

    // 计算用户总数来决定是否为超级管理员
    const userCount = await this.usersRepository.count();

    // 创建新用户
    const newUser = new User();
    newUser.username = username;
    newUser.password = CryptoJS.MD5(password.trim()).toString();
    newUser.nickname = nickname;
    newUser.isSuperAdmin = userCount === 0; // 第一个注册的用户为超级管理员

    return this.usersRepository.save(newUser);
  }

  async initDefaultUser() {
    const count = await this.usersRepository.count();
    if (count === 0) {
      // 创建默认管理员账号
      const defaultAdmin = new User();
      defaultAdmin.username = 'admin';
      defaultAdmin.password = CryptoJS.MD5('admin').toString(); // admin的MD5值
      defaultAdmin.nickname = '管理员';
      defaultAdmin.isSuperAdmin = true;
      await this.usersRepository.save(defaultAdmin);
      console.log('Default admin user created');
    }
  }
} 